# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.


from . import models

from odoo import api, SUPERUSER_ID


def _update_account(env, company, codes, vals_fn):
    chart_template = env.ref(
        'l10n_cn.l10n_chart_china_small_business')

    for account_template in chart_template.account_ids.filtered(
            lambda template: template.code in codes):
        acc = env['account.account'].search(
            [('code', '=', account_template.code + '00'),
             ('company_id', '=', company.id)], limit=1)

        vals = vals_fn(account_template)
        acc.write(vals)


def update_account_name(env, company):
    codes = ['2241', '2501']
    _update_account(
        env, company, codes,
        lambda account_template: {'name': account_template.name})


def update_account_user_type(env, company):
    codes = ['1123']
    _update_account(
        env,  company, codes,
        lambda account_template: {
            'user_type_id': account_template.user_type_id.id,
            'internal_type': account_template.user_type_id.type,
            'reconcile': account_template.reconcile
        })


def init_settings(env):
    chart_template = env.ref(
        'l10n_cn.l10n_chart_china_small_business')

    for company in env['res.company'].search([('chart_template_id', '=', chart_template.id)]):
        chart_template._set_company_transfer_account(company)
        update_account_name(env,  company)
        update_account_user_type(env, company)


def load_translations(env):
    env.ref('l10n_cn.l10n_chart_china_small_business').process_coa_translations()

# def load_translations(cr, registry):
#     env = api.Environment(cr, SUPERUSER_ID, {})


def load_po_overwrite(env):
    module = env['ir.module.module'].search([('name', '=', 'l10n_cn_patch')])
    module._update_translations(overwrite=True)


def post_init(cr, registry):
    env = api.Environment(cr, SUPERUSER_ID, {})
    print('post_init in l10n patch 1,', env)
    # 覆盖翻译
    load_po_overwrite(env)
    print('post_init in l10n patch 2,load_po_overwrite ok')
    load_translations(env)
    print('post_init in l10n patch 3,load_translations ok')
    init_settings(env)
    print('post_init in l10n patch 4, init_settings, ok')
